import { getRequest } from "./api";

export const initMenu = (router, store) => {
  if (store.state.routes.length > 0) {
    return;
  }

  getRequest("/getMenu/data").then((resp) => {
    if (resp) {
    
      //格式化
      let fmtRoutes = formatRoutes(resp.data.menu);
      for (let i = 0; i < fmtRoutes.length; i++) {
       router.addRoute(fmtRoutes[i]);
      }
      // router.addRoutes(fmtRoutes);

      //router.addRoutes(fmtRoutes) ;
      // console.log(fmtRoutes);
      store.commit("initRoutes", fmtRoutes);
    }
  });
};

//格式化
export const formatRoutes = (routes) => {
  // 返回的数据格式
  let fmRoutes = [];
  routes.forEach((router) => {
    //批量的变量定义
    let { path, component, name , meta ,  icon, children } = router;

    if (children && children instanceof Array) {
      children = formatRoutes(children);
    }
    let fmRouter = {
      path: path,
      name: name,
      meta :meta , 
      icon: icon,
      children: children,
      component(resolve) {
        if (component.startsWith("Home")) {
          require(["../views/" + component + ".vue"], resolve);
        } else if (component.startsWith("UserList")) {
          require(["../views/user/" + component + ".vue"], resolve);
        } else if (component.startsWith("BannerSetting")) {
          require(["../views/home/" + component + ".vue"], resolve);
        } else if (component.startsWith("TagSetting")) {
          require(["../views/home/" + component + ".vue"], resolve);
        } else if (component.startsWith("CategorySetting")) {
          require(["../views/home/" + component + ".vue"], resolve);
        } else if (component.startsWith("ProductList")) {
          require(["../views/product/" + component + ".vue"], resolve);
        } else if (component.startsWith("DisplayList")) {
          require(["../views/product/" + component + ".vue"], resolve);
        }else if (component.startsWith("OrderList")) {
          require(["../views/order/" + component + ".vue"], resolve);
        }else if (component.startsWith("QuantityCharts")) {
          require(["../views/statistical/" + component + ".vue"], resolve);
        }else if(component.startsWith("OrderCharts")){
          require(["../views/statistical/" + component + ".vue"], resolve);
        }
      },
    };
    fmRoutes.push(fmRouter);
  });
  return fmRoutes;
};
